package io.github.leon406.capp.base.mvp

import android.graphics.drawable.AnimationDrawable
import android.view.View
import io.github.leon406.capp.R
import kotlinx.android.synthetic.main.layout_error.*
import kotlinx.android.synthetic.main.layout_loading.*
import kotlinx.android.synthetic.main.layout_root.*


/**
 * Author : Leon Shih
 * Time   :2018/8/13 0013 11:57
 * E-mail :deadogone@gmail.com    :
 * Desc   :Mvp Activity base class
 */
abstract class LCEMvpActivity<V : IView, P : IPresenter<V>> : MvpActivity<V, P>() {
    lateinit var animationDrawable: AnimationDrawable
    lateinit var content: View
    lateinit var errorView: View
    lateinit var loadingView: View
    override fun bindLayout() = R.layout.layout_root


    override fun onViewInit() {
        vs_loading.layoutResource = bindLoading()
        vs_error.layoutResource = bindError()
        vs_content.layoutResource = bindContent()
        loadingView = vs_loading.inflate()
        errorView = vs_error.inflate()
        content = vs_content.inflate()

        initLoadingAndErrorView()

        onContentViewInit()
    }

    open fun bindLoading() = R.layout.layout_loading
    open fun bindError() = R.layout.layout_error

    open fun initLoadingAndErrorView() {
        animationDrawable = loading_view.drawable as AnimationDrawable
        btn_reload.setOnClickListener {
            reLoad()
        }
    }

    abstract fun onContentViewInit()

    fun reLoad() {}

    abstract fun bindContent(): Int

    fun showLoading() {
        setViewState(true, false, false)
    }

    fun showContent() {
        setViewState(false, false, true)
    }

    fun showError() {
        setViewState(false, true, false)
    }

    private fun setViewState(showLoading: Boolean, showError: Boolean, showContent: Boolean) {
        loadingView.visibility = if (showLoading) View.VISIBLE else View.GONE
        errorView.visibility = if (showError) View.VISIBLE else View.GONE
        content.visibility = if (showContent) View.VISIBLE else View.GONE
        if (showLoading) {
            animationDrawable.start()
        } else {
            animationDrawable.stop()
        }
    }
}